import { View, Text } from '@tarojs/components'
import { useState, useEffect } from 'react'
import { 
  Card, 
  Button, 
  Tag,
  Empty,
  Loading
} from '@nutui/nutui-react-taro'
import Taro, { useLoad } from '@tarojs/taro'
import { orderApi, userApi, serviceApi } from '../../api/index'

export default function MockDemo() {
  const [orders, setOrders] = useState([])
  const [userInfo, setUserInfo] = useState(null)
  const [services, setServices] = useState([])
  const [loading, setLoading] = useState(false)

  useLoad(() => {
    loadData()
  })

  const loadData = async () => {
    setLoading(true)
    try {
      // 并行请求多个接口
      const [orderData, userData, serviceData] = await Promise.all([
        orderApi.getOrderList(),
        userApi.getUserInfo(),
        serviceApi.getServiceList()
      ])
      
      setOrders((orderData && orderData.list) ? orderData.list : [])
      setUserInfo(userData || null)
      setServices(serviceData || [])
      
      Taro.showToast({
        title: 'Mock 数据加载成功',
        icon: 'success'
      })
    } catch (error) {
      console.error('加载数据失败:', error)
      Taro.showToast({
        title: '加载失败',
        icon: 'error'
      })
    } finally {
      setLoading(false)
    }
  }

  const handleCancelOrder = async (orderId) => {
    try {
      await orderApi.cancelOrder(orderId)
      Taro.showToast({
        title: '订单取消成功',
        icon: 'success'
      })
      // 重新加载订单列表
      loadData()
    } catch (error) {
      console.error('取消订单失败:', error)
    }
  }

  const getStatusColor = (status) => {
    const colors = {
      1: 'warning',  // 待服务
      2: 'primary',  // 服务中
      3: 'success',  // 已完成
      4: 'danger'    // 已取消
    }
    return colors[status] || 'default'
  }

  if (loading) {
    return (
      <View className='mock-demo-page'>
        <Loading direction='vertical'>加载中...</Loading>
      </View>
    )
  }

  return (
    <View className='mock-demo-page'>
      {/* 用户信息展示 */}
      {userInfo && (
        <Card className='user-info-card'>
          <View className='user-info'>
            <Text className='title'>用户信息 (Mock 数据)</Text>
            <View className='info-item'>
              <Text>姓名: {userInfo.name}</Text>
            </View>
            <View className='info-item'>
              <Text>电话: {userInfo.phone}</Text>
            </View>
            <View className='info-item'>
              <Text>余额: ¥{userInfo.balance}</Text>
            </View>
            <View className='info-item'>
              <Text>积分: {userInfo.points}</Text>
            </View>
          </View>
        </Card>
      )}

      {/* 服务列表展示 */}
      {services.length > 0 && (
        <Card className='services-card'>
          <View className='services-info'>
            <Text className='title'>服务类型 (Mock 数据)</Text>
            <View className='services-grid'>
              {services.map(service => (
                <View key={service.id} className='service-item'>
                  <Text className='service-name'>{service.name}</Text>
                  <Text className='service-price'>¥{service.price}/{service.unit}</Text>
                  <View className='service-tags'>
                    {service.tags.map(tag => (
                      <Tag key={tag} size='small' type='primary'>{tag}</Tag>
                    ))}
                  </View>
                </View>
              ))}
            </View>
          </View>
        </Card>
      )}

      {/* 订单列表展示 */}
      <Card className='orders-card'>
        <View className='orders-header'>
          <Text className='title'>订单列表 (Mock 数据)</Text>
          <Button size='small' onClick={loadData}>刷新数据</Button>
        </View>
        
        {orders.length === 0 ? (
          <Empty description='暂无订单数据' />
        ) : (
          <View className='orders-list'>
            {orders.map(order => (
              <Card key={order.id} className='order-item'>
                <View className='order-header'>
                  <Text className='order-no'>订单号: {order.orderNo}</Text>
                  <Tag type={getStatusColor(order.status)}>{order.statusText}</Tag>
                </View>
                
                <View className='order-content'>
                  <View className='order-info'>
                    <Text>服务类型: {order.serviceType}</Text>
                  </View>
                  <View className='order-info'>
                    <Text>服务时间: {order.serviceTime}</Text>
                  </View>
                  <View className='order-info'>
                    <Text>服务地址: {order.address}</Text>
                  </View>
                  <View className='order-info'>
                    <Text>订单金额: ¥{order.amount}</Text>
                  </View>
                  <View className='order-info'>
                    <Text>创建时间: {order.createTime}</Text>
                  </View>
                </View>
                
                {order.status === 1 && (
                  <View className='order-actions'>
                    <Button 
                      size='small' 
                      type='danger'
                      onClick={() => handleCancelOrder(order.id)}
                    >
                      取消订单
                    </Button>
                  </View>
                )}
              </Card>
            ))}
          </View>
        )}
      </Card>

      {/* API 测试按钮 */}
      <Card className='api-test-card'>
        <View className='api-test'>
          <Text className='title'>API 测试</Text>
          <View className='test-buttons'>
            <Button 
              size='small' 
              type='primary'
              onClick={() => orderApi.createOrder({
                serviceType: '测试服务',
                serviceTime: '2025-01-28 15:00',
                address: '测试地址'
              })}
            >
              创建订单
            </Button>
            <Button 
              size='small' 
              onClick={loadData}
            >
              重新加载
            </Button>
          </View>
        </View>
      </Card>
    </View>
  )
}